from bot.enterprise_wechat_gpt.config.conf import *
import re
from bot.enterprise_wechat_gpt.util.constant_role_name import *
from bot.enterprise_wechat_gpt.util.tair_util import TairUtil

tair = TairUtil().tair


# 情况0：对话轮次
def check_communicate_epoch(conversation_history, user_id):
    transfer_detail = {'transfer_flag': False, 'transfer_reason': '对话轮次-不足3轮'}
    Nuser_cnt = [0 if USER in item else 1 for item in conversation_history]
    if sum(Nuser_cnt) > 4:
        transfer_detail['transfer_flag'] = True
        transfer_detail['transfer_reason'] = '对话轮次-大于3次'
        logging.info(f"userId:[{user_id}] 发生转人操作 transfer_detail:{transfer_detail}")
        return transfer_detail
    return transfer_detail


# 情况1：字符不合法
urls = ["http://3.cn/10-bcNHyX", "http://3.cn/10bc-6rUG"]
def check_api_return(llm_res_content):  # 大模型返回结果格式不对
    if llm_res_content is None or llm_res_content == '':   # 内容为空
        return True
    eng_char = re.compile(r'[A-Za-z]')
    if type(llm_res_content) is not str:   # 非字符串
        return False
    llm_res_replace = llm_res_content.replace(urls[0], '').replace(urls[1], '')
    if bool(re.match(eng_char, llm_res_replace)):   # 包含非金条/信用卡链接的英文字母(英文单词)
        return True
    return False


# 情况2：数据类型非文本
transfer_reason1 = ["image", "voice", "weapp"]  # 聊天数据类型
def check_data_type(conversation_history, user_id):  # 用户说话的数据类型
    default_type = 'text'
    transfer_detail = {'transfer_flag': False, 'transfer_reason': default_type}
    for item in conversation_history[::-1]:
        type_ = item.get('msg_type', default_type)
        if type_ in transfer_reason1 or type_ != 'text':   # 图像声音小程序类型消息 | 非text类型消息
            transfer_detail['transfer_flag'] = True
            transfer_detail['transfer_reason'] = type_
            logging.info(f"userId:[{user_id}] 发生转人操作 transfer_detail:{transfer_detail}")
            return transfer_detail
        elif type_ is None:
            transfer_detail['transfer_flag'] = True
            transfer_detail['transfer_reason'] = 'msg_type为空'
            logging.info(f"userId:[{user_id}] 发生转人操作 transfer_detail:{transfer_detail}")
            return transfer_detail
    return transfer_detail


# 情况3：用户情景命中敏感信息
transfer_reason2 = ["白条", "分分卡", "黑卡", "小金库"]  # 产品范围
transfer_reason3 = ["买房", "房贷", "理财", "投资"]  # 借款用途
transfer_reason4 = ["军人", "学生", "企业主"]  # 用户身份
transfer_reason5 = ["逾期"]  # 逾期风险
def check_situation(user_question, user_situation, user_id):  # 用户情景对产品/借款用途/用户身份的识别
    transfer_detail = {'transfer_flag': False, 'transfer_reason': 'situation_OK'}
    if '想要优惠券' in user_situation and '不想要优惠券' not in user_situation:
        transfer_detail['transfer_flag'] = True
        transfer_detail['transfer_reason'] = '想要优惠券'
        logging.info(f"userId:[{user_id}] 发生转人操作 转人原因: 想要优惠券")
        return transfer_detail

    transfer_reasons = [transfer_reason2, transfer_reason3, transfer_reason4, transfer_reason5]
    for transfer_reasonI in transfer_reasons:
        for situation in transfer_reasonI:
            if situation in user_situation or situation in user_question:
                transfer_detail['transfer_flag'] = True
                transfer_detail['transfer_reason'] = situation
                logging.info(f"userId:[{user_id}] 发生转人操作 transfer_detail:{transfer_detail}")
                return transfer_detail
    # if '产品' in user_situation and '金条' not in user_situation:   # 情景有产品信息，但是非金条产品
    #     transfer_detail['transfer_flag'] = True
    #     transfer_detail['transfer_reason'] = '非金条产品'
    #     logging.info(f"userId:[{user_id}] 发生转人操作 transfer_detail:{transfer_detail}")
    #     return transfer_detail
    return transfer_detail


# 情况4：需要补充外部系统信息
pattern1 = [r"申请|看看", r"优惠券|息费折扣券"]   # 机器人去给用户申请优惠券了，机器人无法确认优惠券是否申请完成，转人
patterns = [pattern1]   #######################TODO 补充
def outer_system(final_utter, user_id):
    transfer_detail = {'transfer_flag': False, 'transfer_reason': '需要外部系统信息'}
    for pattern in patterns:
        result = [not re.findall(pt, final_utter) == [] for pt in pattern]
        if True in result:
            transfer_detail['transfer_flag'] = True
            transfer_detail['transfer_reason'] = 'outerInfo_' + ''.join(pattern[i] for i, res in enumerate(result) if res is True)
            logging.info(f"userId:[{user_id}] 发生转人操作 transfer_detail:{transfer_detail}")
            return transfer_detail
    return transfer_detail






# 情况5：复杂金条业务情景
group1 = ["额度正常", "已获得优惠券", "借款失败"]
group2 = ["有额度", "已获得优惠券", "无法正常借款"]
groups = [group1, group2]   #######################TODO 补充
def complex_situation(user_situation, user_question, user_id):
    transfer_detail = {'transfer_flag': False, 'transfer_reason': '未命中金条复杂情景'}
    for group in groups:
        flag = False in [gp in user_situation+user_question for gp in group]
        if not flag:
            transfer_detail['transfer_flag'] = True
            transfer_detail['transfer_reason'] = '&'.join(group)
            logging.info(f"userId:[{user_id}] 发生转人操作 transfer_detail:{transfer_detail}")
            return transfer_detail
    return transfer_detail
# 用户帐户显示43000的剩余额度，需要2万，坐席申请了一张6折券，用户借款失败。
# 当前借款状态：借款失败｜当前优惠券状态：已获得优惠券｜当前账户状态：额度正常 & 用户无法正常借款。




if __name__ == '__main__':
    # final_utter = '那太棒了！[憨笑]为了满足您更多的资金需求，您可以考虑申请一张京东联名信用卡，额度最高20万，适合线上线下消费，享有免息期最长50天的优惠，使用方便灵活。您可以先在京东金融APP中了解一下，我也可以为您提供帮助和咨询。祝您生活愉快！如有疑问，请随时联系我。'
    # res = [not re.findall(pt, final_utter) == [] for pt in pattern1]
    # res = outer_system(final_utter, "123")
    # print(res)
    pass








